/**
 * 
 */
package neptune.web.server.security;

import it.robertobifulco.ias.PermissionHandler;
import it.robertobifulco.ias.UnauthorizedOperationException;
import it.robertobifulco.ias.principalmanager.Principal;
import neptune.manager.storage.ExperimentRepositoryException;
import neptune.web.client.model.DefaultRoles;
import neptune.web.server.ApplicationManager;
import neptune.web.server.InitializationException;
import neptune.web.server.operations.DeleteExperiment;
import neptune.web.server.operations.GetExperiment;

/**
 * @author Roberto Bifulco [info@robertobifulco.it, robertobifulco.it]
 *
 */
public class GetExperimentPH implements PermissionHandler {

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.PermissionHandler#verifyPermission(java.lang.String,
	 *      it.robertobifulco.ias.principalmanager.Principal)
	 */
	public void verifyPermission(String operationName, Principal principal)
			throws UnauthorizedOperationException {
		if (operationName.equals(GetExperiment.ID)){
//			Il system admin ha diritto di cancellare qualsiasi esperimento
			if(principal.getRole().equals(DefaultRoles.SYSTEM_ADMIN))
				return;
			
			throw new UnauthorizedOperationException(
					"Not enough infos to concede the permission");
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see it.robertobifulco.ias.PermissionHandler#verifyPermission(java.lang.String,
	 *      it.robertobifulco.ias.principalmanager.Principal,
	 *      it.robertobifulco.ias.PermissionExtraInfos)
	 */
	public void verifyPermission(String operationName, Principal principal,
			Object extraInfos) throws UnauthorizedOperationException {
		if (!operationName.equals(DeleteExperiment.ID))
			return;

//		Il system admin ha diritto di cancellare qualsiasi esperimento
		if(principal.getRole().equals(DefaultRoles.SYSTEM_ADMIN))
			return;		
		
		String experimentId = (String) extraInfos;
		try {
			String expAdmin = ApplicationManager.getApplicationManager()
					.getNeptuneManager().getExperimentsRepository()
					.getExperimentAdmin(experimentId);

			if (expAdmin.equals(principal.getId()))
				return;
			
			String[][] expUsers = ApplicationManager.getApplicationManager()
			.getNeptuneManager().getExperimentsRepository()
			.getExperimentUsers(experimentId);
			
			for(int i=0; i < expUsers.length ; ++i){
				if(expUsers[i][0].equals(principal.getId()))
					return;
			}

		} catch (ExperimentRepositoryException e) {
			throw new UnauthorizedOperationException(e);
		} catch (InitializationException e) {
			e.printStackTrace();
			throw new UnauthorizedOperationException(e);
		}

		throw new UnauthorizedOperationException("Operation " + operationName
				+ " is unauthorized for principal " + principal.getId());
	}

}
